/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.suli.outHouse.rest;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.suli.outHouse.domain.Orders;
import me.zhengjie.suli.outHouse.repository.OrdersRepository;
import me.zhengjie.suli.outHouse.service.OrdersService;
import me.zhengjie.suli.outHouse.service.dto.OrdersQueryCriteria;
import me.zhengjie.suli.outHouse.service.mapstruct.OrdersMapper;
import me.zhengjie.suli.tasks.domain.Tasks;
import me.zhengjie.suli.tasks.repository.TasksRepository;
import me.zhengjie.suli.wcs.service.AgvTasksService;
import me.zhengjie.util.CommonUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Objects;

/**
* @website https://eladmin.vip
* @author WYH
* @date 2024-02-01
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "出库计划管理")
@RequestMapping("/api/orders")
public class OrdersController {

    private final OrdersService ordersService;
    private final CommonUtil commonUtil;
    private final OrdersRepository ordersRepository;
    private final AgvTasksService agvTasksService;
    private final OrdersMapper ordersMapper;
    private final TasksRepository tasksRepository;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('orders:list')")
    public void exportOrders(HttpServletResponse response, OrdersQueryCriteria criteria) throws IOException {
        ordersService.download(ordersService.queryOrderByOut(criteria), response);
    }

    @GetMapping
    @Log("查询出库计划")
    @ApiOperation("查询出库计划")
    @PreAuthorize("@el.check('orders:list')")
    public ResponseEntity<Object> queryOrders(OrdersQueryCriteria criteria, Pageable pageable) throws ParseException {
        return new ResponseEntity<>(ordersService.queryOrder(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增出库计划")
    @ApiOperation("新增出库计划")
    @PreAuthorize("@el.check('orders:add')")
    public ResponseEntity<Object> createOrders(@Validated @RequestBody Orders resources){
        return new ResponseEntity<>(ordersService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改出库计划")
    @ApiOperation("修改出库计划")
    @PreAuthorize("@el.check('orders:edit')")
    public ResponseEntity<Object> updateOrders(@Validated @RequestBody Orders resources){
        ordersService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除出库计划")
    @ApiOperation("删除出库计划")
    @PreAuthorize("@el.check('orders:del')")
    public ResponseEntity<Object> deleteOrders(@RequestBody String[] ids) {
        ordersService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @PostMapping("/sccs-byCar")
    @Log("销售随车单")
    @ApiOperation("销售随车单")
    public String sccsByCar(@RequestBody String param){
        return ordersService.byCarDocument(param);
    }


    @PostMapping("/roll-byCar")
    @Log("转仓随车单")
    @ApiOperation("转仓随车单")
    public String rollByCar(@RequestBody String param){
        return ordersService.rollByCar(param);
    }

    /**
     * 接受SCCS推送的销售指令
     */
    @PostMapping("/receive-sales-instructions")
    @Log("接受SCCS推送的销售指令")
    @ApiOperation("接受SCCS推送的销售指令")
    public String receiveSalesInstructions(@RequestBody String param){
        return ordersService.receiveSalesInstructions(param);
    }

    /**
     * 接受成本中心出库
     */
    @PostMapping("/costCenterUse")
    @Log("成本中心领用333")
    @ApiOperation("成本中心领用333")
    public String costCenterUse(@RequestBody String param){
        return ordersService.costCenterUse(param);
    }


    @PostMapping("/generateOrderTasks")
    @Log("新增出库任务")
    @ApiOperation("新增出库任务")
    public Object addOutBoundTask(@RequestBody String id){
        return ordersService.addOutBoundTask(id);
    }

    @PostMapping("/giveOrder")
    @Log("生成出库单")
    @ApiOperation("生成出库单")
    public ResponseEntity<Object> sendCodeToSCCS(@RequestBody String param){
        Tasks bySourceCodeTop = tasksRepository.findBySourceCodeTop(param);
        JSONObject jsonObject = new JSONObject();
        Orders bySourceDocument = ordersRepository.findBySourceDocument(param);
        if (!Objects.isNull(bySourceDocument)){
            if (bySourceDocument.getOrderType() == 1){
                if (bySourceDocument.getOrderStatus() == 6){
                    return new ResponseEntity<>("1",HttpStatus.OK);
                }else if (bySourceDocument.getOrderStatus() == 2){
                    return new ResponseEntity<>(null,HttpStatus.OK);
                }else{
                    return new ResponseEntity<>("2",HttpStatus.OK);
                }

            } else if (bySourceDocument.getOrderType() == 2) {
                if (bySourceDocument.getOrderStatus() == 6){
                    return new ResponseEntity<>("1",HttpStatus.OK);
                }else if (bySourceDocument.getOrderStatus() == 2){
                    return new ResponseEntity<>(null,HttpStatus.OK);
                }else{
                    return new ResponseEntity<>("2",HttpStatus.OK);
                }

            }else{
                return new ResponseEntity<>("2",HttpStatus.OK);
            }

        }else {
            if (null != bySourceCodeTop) {
                return new ResponseEntity<>("3",HttpStatus.OK);
            }
            jsonObject.put("list", param);
            String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSSelectList", jsonObject);
            String resp = StrUtil.strip(s, "\"").replaceAll("\\\\","");
            JSONObject jsonObject1 = JSON.parseObject(resp);
            return new ResponseEntity<>(jsonObject1,HttpStatus.OK);
        }

    }


    @PostMapping("/returnLocation")
    @ApiOperation("空料箱回库扫描料箱码")
    public ResponseEntity<Object> returnLocation(@RequestBody String param){
        return new ResponseEntity<>(ordersService.returnLocation(param),HttpStatus.OK);
    }

    @PostMapping("/queryOrder")
    @ApiOperation("空料箱回库扫描料箱码")
    public ResponseEntity<Object> queryOrder(@RequestBody String param){
        return new ResponseEntity<>(ordersService.returnLocation(param),HttpStatus.OK);
    }

    @PostMapping("/rePushSccs")
    @ApiOperation("重推sccs")
    public ResponseEntity<Object> rePushSccs(@RequestBody String param){
        return new ResponseEntity<>(ordersService.rePushSccs(param),HttpStatus.OK);
    }

    @AnonymousPostMapping("/outBoundByLocationCode")
    @ApiOperation("料箱回库")
    public ResponseEntity<Object> outboundByLocationCode(@RequestBody String param){
        return new ResponseEntity<>(ordersService.outBoundByLocationCode(param),HttpStatus.OK);
    }

    @AnonymousPostMapping("/getBoxNumber")
    @ApiOperation("根据料箱号查找箱号出货数量")
    public ResponseEntity<Object> getBoxNumberByTrayCode(@RequestBody String param){
        return new ResponseEntity<>(ordersService.getBoxNumberByTrayCode(param),HttpStatus.OK);
    }

    @AnonymousPostMapping("/getZanCunQu")
    @ApiOperation("根据订单id查询暂存区出货数量")
    public ResponseEntity<Object> getZanCunQu(@RequestBody String param){
        return new ResponseEntity<>(ordersService.getCountByOrderId(param),HttpStatus.OK);
    }

    @AnonymousPostMapping("/quXiao")
    @ApiOperation("取消任务")
    public ResponseEntity<Object> quXiao(@RequestBody String param){
        return new ResponseEntity<>(ordersService.quXiao(param),HttpStatus.OK);
    }

    @AnonymousPostMapping("/outBoundReturn")
    @ApiOperation("SCCS触发取消任务")
    public ResponseEntity<Object> outBoundReturn(@RequestBody String param){
        return new ResponseEntity<>(ordersService.quXiao(param),HttpStatus.OK);
    }

    @AnonymousPostMapping("/selectByOrderIdReturn")
    @ApiOperation("少拿出货重新出库")
    public ResponseEntity<Object> selectByOrderIdReturn(@RequestBody String param){
        return new ResponseEntity<>(ordersService.selectOrderById(param),HttpStatus.OK);
    }

    @AnonymousPostMapping("/selectOrderDetailById")
    @ApiOperation("根据出货单id查找")
    public ResponseEntity<Object> selectOrderDetailById(@RequestBody String param){
        return new ResponseEntity<>(ordersService.selectOrderDetailById(param),HttpStatus.OK);
    }

    /**
     * 不分套出库
     * @param param
     * @return
     */
    @AnonymousPostMapping("/fenTaoOutBound")
    @ApiOperation("不分套出库")
    public ResponseEntity<Object> fenTaoOutBound(@RequestBody String param){
        return new ResponseEntity<>(ordersService.fenTaoOutBound(param),HttpStatus.OK);
    }

    /**
     * 胶盖胶脚保护器专用分套出库
     * @param param
     * @return
     */
    @AnonymousPostMapping("/fenTaoOther")
    @ApiOperation("胶盖胶脚保护器专用分套出库")
    public ResponseEntity<Object> fenTaoOther(@RequestBody String param){
        return new ResponseEntity<>(ordersService.fenTaoOther(param),HttpStatus.OK);
    }

    /**
     * 分套出库时先排出的杂料
     * @param param
     * @return
     */
    @AnonymousPostMapping("/fenTaoOtherOne")
    @ApiOperation("分套出库时先排出的杂料")
    public ResponseEntity<Object> fenTaoOtherOne(@RequestBody String param){
        return new ResponseEntity<>(ordersService.fenTaoOtherOne(param),HttpStatus.OK);
    }

    @AnonymousPostMapping("/wanCheng")
    @ApiOperation("手动完成任务")
    public ResponseEntity<Object> wanCheng(@RequestBody String param){
        return new ResponseEntity<>(ordersService.wanCheng(param),HttpStatus.OK);
    }

    /**
     * 根据orderId查找本单据胶盖胶脚的出货数量
     * @param param
     * @return
     */
    @AnonymousPostMapping("/getTaskDetailCountByOrderId")
    @ApiOperation("根据orderId查找本单据胶盖胶脚的出货数量")
    public ResponseEntity<Object> getTaskDetailCountByOrderId(@RequestBody String param){
        return new ResponseEntity<>(ordersService.getTaskDetailCountByOrderId(param),HttpStatus.OK);
    }

    /**
     * 冻结出库
     * @param param
     * @return
     */
    @AnonymousPostMapping("/outBoundByInventory")
    @ApiOperation("冻结出库")
    public ResponseEntity<Object> outBoundByInventory(@RequestBody String param){
        //传参json格式的库存list
        return new ResponseEntity<>(ordersService.outBoundByInventory(param),HttpStatus.OK);
    }

    @PostMapping("/receiveBillNumberFromPDA")
    @ApiOperation("接受PDA推送的出库单号")
    public ResponseEntity<Object> receiveBillNumberFromPDA(@RequestBody String param){
        return new ResponseEntity<>(ordersService.receiveBillNumberFromPDA(param),HttpStatus.OK);
    }

    @PostMapping("/receiveHuiKuBoxNumberFromPDA")
    @ApiOperation("接受PDA推送的出库单号")
    public ResponseEntity<Object> receiveHuiKuBoxNumberFromPDA(@RequestBody String param){
        return new ResponseEntity<>(ordersService.receiveHuiKuBoxNumberFromPDA(param),HttpStatus.OK);
    }

}